package list

import (
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"sync"
)

type SourceList struct {
	Path string
	List map[string]string
	lock sync.Mutex
}

func NewSourceList(path string) (l SourceList) {
	err := l.initList(path)
	if err != nil {
		log.Fatal(err.Error())
	}
	return
}

//设置路径，如果不是绝对路径则转换成绝对路径
func (s *SourceList) setPath(path string) error {
	if !filepath.IsAbs(path) {
		abs, err := os.Getwd()
		if err != nil {
			return err
		}
		path = filepath.Join(abs, path)
	}
	s.Path = path
	return nil
}

func (s *SourceList) initList(path string) (err error) {
	s.List = make(map[string]string)
	s.setPath(path)

	fileinfo, err := ioutil.ReadDir(s.Path)
	if err != nil {
		return
	}

	for _, v := range fileinfo {
		if v.IsDir() {
			continue
		}
		p := filepath.Join(s.Path, v.Name())
		s.List[v.Name()] = p
		log.Println("add ", v.Name(), p)
	}
	log.Printf("Got %d videos\n", len(s.List))
	return
}

func (s *SourceList) Get(name string) (p string) {
	p, _ = s.List[name]
	return
}

func (s *SourceList) IsHave(name string) bool {
	_, ok := s.List[name]
	return ok
}
